//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import type { NodeProps } from "reactflow";
import type { NodeInfo } from '@/api/project_dataview';
import ProjectNodeWrap from '../ProjectNodeWrap';
import { Button, Descriptions, Space, Tag } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import { observer } from 'mobx-react';
import { useDataViewStores } from '@/pages/DataView/store';
import {
    BUG_LEVEL_BLOCKER, BUG_LEVEL_CRITICAL, BUG_LEVEL_MAJOR, BUG_LEVEL_MINOR, BUG_PRIORITY_HIGH, BUG_PRIORITY_IMMEDIATE, BUG_PRIORITY_LOW,
    BUG_PRIORITY_NORMAL, BUG_PRIORITY_URGENT, get as get_issue, ISSUE_STATE_PROCESS,
    ISSUE_TYPE_BUG,
    PROCESS_STAGE_DOING, PROCESS_STAGE_DONE, PROCESS_STAGE_TODO, type GetResponse as GetIssueResponse
} from "@/api/project_issue";
import { get_session } from '@/api/user';
import type * as NoticeType from '@/api/notice_type';
import { listen } from '@tauri-apps/api/event';
import { issueState } from '@/utils/constant';
import moment from 'moment';
import IssueDetailModal from '@/pages/Issue/IssueDetailModal';

const RefBugNode = (props: NodeProps<NodeInfo>) => {
    const dataViewStore = useDataViewStores();

    const [dataResponse, setDataResponse] = useState<GetIssueResponse | null>(null);
    const [showDetailModal, setShowDetailModal] = useState(false);
    const [issueTab, setIssueTab] = useState<"detail" | "subtask" | "mydep" | "depme" | "event" | "comment" | "vote">("detail");

    const loadDataResponse = async () => {
        const sessionId = await get_session();
        const res = await get_issue(sessionId, dataViewStore.projectStore.projectId, props.data.node_data.RefTargetId ?? "");
        setDataResponse(res);
    };

    useEffect(() => {
        loadDataResponse();
    }, []);

    useEffect(() => {
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.IssueNotice?.UpdateIssueNotice != undefined && notice.IssueNotice.UpdateIssueNotice.issue_id == props.data.node_data.RefTargetId) {
                loadDataResponse();
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, []);

    return (
        <ProjectNodeWrap title="缺陷" nodeData={props} canChangeBgColor
            extraButtonList={[
                <Button type="text" icon={<ReloadOutlined />} onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    loadDataResponse();
                }} />
            ]}>
            {dataResponse != null && (
                <>
                    {dataResponse.code != 0 && <span style={{ color: "red" }}>{dataResponse.err_msg}</span>}
                    {dataResponse.code == 0 && (
                        <div>
                            <a style={{ fontSize: "20px", fontWeight: 700 }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setShowDetailModal(true);
                            }}>{dataResponse.info.basic_info.title}</a>

                            <Descriptions column={1}>
                                <Descriptions.Item label="状态">
                                    <div>{issueState[dataResponse.info.state].label}</div>
                                </Descriptions.Item>
                                {dataResponse.info.state == ISSUE_STATE_PROCESS && (
                                    <Descriptions.Item label="处理子阶段">
                                        {dataResponse.info.process_stage == PROCESS_STAGE_TODO && "未开始"}
                                        {dataResponse.info.process_stage == PROCESS_STAGE_DOING && "执行中"}
                                        {dataResponse.info.process_stage == PROCESS_STAGE_DONE && "待检查"}
                                    </Descriptions.Item>
                                )}
                                <Descriptions.Item label="级别">
                                    {dataResponse.info.extra_info.ExtraBugInfo?.level == BUG_LEVEL_MINOR && "提示"}
                                    {dataResponse.info.extra_info.ExtraBugInfo?.level == BUG_LEVEL_MAJOR && "一般"}
                                    {dataResponse.info.extra_info.ExtraBugInfo?.level == BUG_LEVEL_CRITICAL && "严重"}
                                    {dataResponse.info.extra_info.ExtraBugInfo?.level == BUG_LEVEL_BLOCKER && "致命"}
                                </Descriptions.Item>
                                <Descriptions.Item label="优先级">
                                    {dataResponse.info.extra_info.ExtraBugInfo?.priority == BUG_PRIORITY_LOW && "低优先级"}
                                    {dataResponse.info.extra_info.ExtraBugInfo?.priority == BUG_PRIORITY_NORMAL && "正常处理"}
                                    {dataResponse.info.extra_info.ExtraBugInfo?.priority == BUG_PRIORITY_HIGH && "高度重视"}
                                    {dataResponse.info.extra_info.ExtraBugInfo?.priority == BUG_PRIORITY_URGENT && "急需解决"}
                                    {dataResponse.info.extra_info.ExtraBugInfo?.priority == BUG_PRIORITY_IMMEDIATE && "马上解决"}
                                </Descriptions.Item>
                                {dataResponse.info.extra_info.ExtraBugInfo?.software_version != "" && (
                                    <Descriptions.Item label="软件版本">{dataResponse.info.extra_info.ExtraBugInfo?.software_version ?? ""}</Descriptions.Item>
                                )}
                                {dataResponse.info.exec_user_id != "" && (
                                    <Descriptions.Item label="处理人">
                                        {dataResponse.info.exec_display_name}
                                    </Descriptions.Item>
                                )}
                                {dataResponse.info.check_user_id != "" && (
                                    <Descriptions.Item label="验收人">
                                        {dataResponse.info.check_display_name}
                                    </Descriptions.Item>
                                )}
                                {dataResponse.info.has_dead_line_time && (
                                    <Descriptions.Item label="截止时间">
                                        {moment(dataResponse.info.dead_line_time).format("YYYY-MM-DD")}
                                    </Descriptions.Item>
                                )}
                                {dataResponse.info.has_start_time && (
                                    <Descriptions.Item label="预估开始时间">
                                        {moment(dataResponse.info.start_time).format("YYYY-MM-DD")}
                                    </Descriptions.Item>
                                )}
                                {dataResponse.info.has_end_time && (
                                    <Descriptions.Item label="预估完成时间">
                                        {moment(dataResponse.info.end_time).format("YYYY-MM-DD")}
                                    </Descriptions.Item>
                                )}
                                {dataResponse.info.has_estimate_minutes && (
                                    <Descriptions.Item label="预估工时">
                                        {(dataResponse.info.estimate_minutes / 60).toFixed(1)}小时
                                    </Descriptions.Item>
                                )}
                                {dataResponse.info.has_remain_minutes && (
                                    <Descriptions.Item label="剩余工时">
                                        {(dataResponse.info.remain_minutes / 60).toFixed(1)}小时
                                    </Descriptions.Item>
                                )}
                                {dataResponse.info.tag_info_list.length > 0 && (
                                    <Descriptions.Item label="标签">
                                        <Space style={{ flexWrap: "wrap" }}>
                                            {dataResponse.info.tag_info_list.map(tag => (
                                                <Tag key={tag.tag_id} style={{ backgroundColor: tag.bg_color }}>{tag.tag_name}</Tag>
                                            ))}
                                        </Space>
                                    </Descriptions.Item>
                                )}
                            </Descriptions>
                        </div>
                    )}
                </>
            )}
            {dataResponse != null && dataViewStore.projectStore.projectInfo != null && showDetailModal && (
                <IssueDetailModal projectInfo={dataViewStore.projectStore.projectInfo}
                    tagList={dataViewStore.projectStore.tagList}
                    myUserId={dataViewStore.projectStore.myUserId} myDisplayName={dataViewStore.projectStore.myUser?.display_name ?? ""} myLogoUri={dataViewStore.projectStore.myUser?.logo_uri ?? ""}
                    issueType={ISSUE_TYPE_BUG}
                    issueId={props.data.node_data.RefTargetId ?? ""}
                    issueTab={issueTab}
                    onClose={() => setShowDetailModal(false)}
                    onChange={newTab => setIssueTab(newTab)}
                    onClickIssue={() => {
                        //do nothing
                    }} />
            )}
        </ProjectNodeWrap>
    )
};

export default observer(RefBugNode);
